﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DefCore.Tools
{
    public static class ShadowedOutlineBuilder
    {
        public static Texture2D BuildBlackShadowedOutline(Texture2D texture, Vector2 borderSize)
        {
            RenderTarget2D shadowTarget = new RenderTarget2D(Objects.GameObject.GraphicsDevice, texture.Width + (int)borderSize.X, texture.Height + (int)borderSize.Y,
                false, SurfaceFormat.Color, DepthFormat.None);

            Objects.GameObject.GraphicsDevice.SetRenderTarget(shadowTarget);
            Objects.GameObject.GraphicsDevice.Clear(Color.Transparent);
            using (SpriteBatch shadowOutlineBatch = new SpriteBatch(Objects.GameObject.GraphicsDevice))
            {
                shadowOutlineBatch.Begin();
                shadowOutlineBatch.Draw(texture, new Rectangle(0, 0, texture.Width + (int)borderSize.X, texture.Height + (int)borderSize.Y), Color.Black);
                shadowOutlineBatch.End();
            }

            Objects.GameObject.GraphicsDevice.SetRenderTarget(null);
            return shadowTarget; 
        }
        
        public static Texture2D BuildColourableShadowedOutline(Texture2D texture, Vector2 borderSize)
        {
            RenderTarget2D shadowTarget = new RenderTarget2D(Objects.GameObject.GraphicsDevice, texture.Width + (int)borderSize.X, texture.Height + (int)borderSize.Y,
                false, SurfaceFormat.Color, DepthFormat.None);

            Objects.GameObject.GraphicsDevice.SetRenderTarget(shadowTarget);
            Objects.GameObject.GraphicsDevice.Clear(Color.Transparent);
            using (SpriteBatch shadowOutlineBatch = new SpriteBatch(Objects.GameObject.GraphicsDevice))
            {
                shadowOutlineBatch.Begin();
                shadowOutlineBatch.Draw(texture, new Rectangle(0,0, texture.Width + (int)borderSize.X, texture.Height + (int)borderSize.Y), Color.Black);
                shadowOutlineBatch.End();
            }

            Objects.GameObject.GraphicsDevice.SetRenderTarget(null);
            Texture2D holder = shadowTarget;

            //Replace all black pixels with White
            Color[] data = new Color[shadowTarget.Width * shadowTarget.Height];
            holder.GetData<Color>(data);
            for (int i = 0; i < data.Length; i++)
            {
                if(data[i] != Color.Transparent)
                    data[i] = Color.White;
            }

            holder.SetData(data);

            return holder;
        }
    }
}
